// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    beforePlanned: true,
    imgPath: '/images',
    baseUrl: '',

    //channel
    channel: '',
    is_share: '',
    //code
    code: '',
    //hash
    hash: 'lhbb',
    //nickname
    nickname: '',
    //head_image
    head_image: '',
    url: '',
    currentPage: '', // 当前页面，登录后要返回的页面
    aid: 0,
    goods_id:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
    //保存this指针，在回调函数里使用
    //工具对象
    const util = require("../../utils/util")
    let that = this;
    let channel = options.channel;
    let is_channel = options.is_channel;  // 购买渠道 
    let is_share = options.is_share;
    let aid = options.aid; //文章id
    let goods_id = options.goods_id; //商品id
    let card_sn = options.card_sn; //成长卡id
    let query = options.query;
    let currentPage = options.currentPage;
    this.setData({
      url: query,
      currentPage
    });
    //设置到全局变量
    util.setChannel(channel);
    //设置到本页面
    this.setData({
      channel: channel,
      is_share: is_share,
      aid: aid,
      goods_id:goods_id,
      card_sn:card_sn,
      is_channel:is_channel
    })
    if (channel) {
      wx.setStorageSync('channel', options.channel);
      //  console.log('channel',options.channel);
    }
    if (is_share) {
      wx.setStorageSync('is_share', options.is_share);
      //  console.log('is_share',options.is_share);
    }
    //const app=getApp();
    this.setData({
      beforePlanned: util.getBeforePlanned(),
      imgPath: util.getImgPath(),
      baseUrl: util.getBaseUrl()
    })

    let token = wx.getStorageSync('token');
    if (!token) {
      //登录服务器
      util.loginWx({
        success: (res) => {
         // console.log("util.loginWx,res", res)
          that.setData({
            code: res.code
          });
          // console.log("this.data",this.data)
          //保存全局code
          util.setCode(res.code);
          //保存到本地缓存
          wx.setStorageSync('code', res.code)
          //   console.log('获取登陆code=======',res.code);
          //继续处理登录
          that.processLogin()
        },
      })

    } else {
      that.processLogin()
    }


  },

  /**
   * 处理登录
   * @param {*} that this指针
   */
  processLogin() {
    const that = this;

    const util = require("../../utils/util");

    // 从缓存中取得userInfo
    let userInfo = wx.getStorageSync('userInfo')
     console.log("userInfo", userInfo)

    //设置全局userInfo
    util.setUserInfo(userInfo);

    // let userInfo = util.getUserInfo();
    if (userInfo) {
      // console.log("jumpToPage")

      // that.setData({
      //   nickname: userInfo.nickName,
      //   head_image: userInfo.avatarUrl
      // })
      // console.log("this.data", this.data)
      //wx.setStorageSync('token', '');
      //全局token
      let token =  wx.getStorageSync('token'); //util.getToken();
      if (!token) {
        //登录服务器
        that.loginServer();   // 改 先注释
      //  console.log('loginServer',token);  
      } else {
        //刷新全局数据
        that.refreshHome();  
     //   console.log('refreshHome',token);
        //跳转
        //that.jumpToPage();
      }
    

    } else {
      //没有用户信息
      wx.showModal({
        title: '授权',
        content: '小程序要取得您的微信头像和昵称，请点【确定】继续',
        complete: async (res) => {
          //取消
          if (res.cancel) {

          }
          //确定
          if (res.confirm) {

            //登录服务器
            that.loginServer();

            //取得用户信息
            await that.getUserInfo();

            //跳转
            //  that.jumpToPage();
          }
        }
      })
    }
  },
  /**
   * 跳转页面
   */
  jumpToPage() {
     const util = require("../../utils/util")
    // if (this.data.url == 'chengzhang') {
    //   wx.redirectTo({
    //     url: '/pages/chengZhangKa/index'
    //   })
    // }
    if (this.data.beforePlanned) { // 没有成为会员
      // 扫码
      if (this.data.url == 'scannCode') {
        wx.redirectTo({
          url: '/pages/codeing/codeing',
        })
      } else if (this.data.url == 'chengzhangka') {
        wx.redirectTo({
          url: '/pages/chengZhangKa/index',
        })
      } else if (this.data.url == 'wenzhang') {
        wx.redirectTo({
          url: '/pages/parenting/article?aid=' + this.data.aid,
        }) // 分享
      } else if (this.data.url == 'fengxiang') {
        util.setTabbarActive('plan');
        wx.redirectTo({
          url: '/pages/plan/joinPlan?channel=' + this.data.channel + '&is_share=' + this.data.is_share
        })
      } else if (this.data.url == 'paySuccess') { // 成功支付
        wx.redirectTo({
          url: '/pages/orderSheet/paySuccess'
        })
      } else if (this.data.url == 'wenzhang') {
        wx.redirectTo({
          url: '/pages/parenting/article?aid=' + this.data.aid
        })
      } else if (this.data.url == 'nologin') {
        wx.redirectTo({
          url: this.data.currentPage
        })
      } else if(this.data.url == 'join_add'){
          wx.redirectTo({
            url: '/pages/submiting/submiting'
          })
      }else if(this.data.url == 'detail_shop'){
        wx.redirectTo({
          url: '/pages/goods/detail?goods_id='+ this.data.goods_id,
        })
      }else if(this.data.url == 'viptry'){
        wx.redirectTo({
          url: '/pages/tryvip/tryvip?card_sn='+ this.data.card_sn + '&is_channel=' + this.data.is_channel,
        })
     }else if(this.data.url == 'vipv'){
      wx.redirectTo({
        url: '/pages/openingvip/openingvip?card_sn='+ this.data.card_sn + '&is_channel=' + this.data.is_channel,
      })
      }else{
        wx.redirectTo({
          url: '/pages/service/index',
        })
      }
    } else { //成为会员
      if (this.data.url == 'scannCode') {
        wx.redirectTo({
          url: '/pages/codeing/codeing',
        })
      } else if (this.data.url == 'chengzhangka') {
        wx.redirectTo({
          url: '/pages/chengZhangKa/index',
        })
      } else if (this.data.url == 'wenzhang') {
        wx.redirectTo({
          url: '/pages/parenting/article?aid=' + this.data.aid,
        })
      } else if (this.data.url == 'fengxiang') {
        util.setTabbarActive('plan');
        wx.redirectTo({
          url: '/pages/plan/joinPlan?channel=' + this.data.channel + '&is_share=' + this.data.is_share
        })
      } else if (this.data.url == 'paySuccess') { // 成功支付
        wx.redirectTo({
          url: '/pages/orderSheet/paySuccess'
        })
      } else if (this.data.url == 'wenzhang') {
        wx.redirectTo({
          url: '/pages/parenting/article?aid=' + this.data.aid
        })
      } else if (this.data.url == 'nologin') {
        wx.redirectTo({
          url: this.data.currentPage
        })
      }else if(this.data.url == 'join_add'){
        wx.redirectTo({
          url: '/pages/submiting/submiting'
        })
       }else if(this.data.url == 'detail_shop'){
        wx.redirectTo({
          url: '/pages/goods/detail?goods_id='+ this.data.goods_id,
        })
       }else if(this.data.url == 'viptry'){
        wx.redirectTo({
          url: '/pages/tryvip/tryvip?card_sn='+ this.data.card_sn + '&is_channel=' + this.data.is_channel,
        })
      }else if(this.data.url == 'vipv'){
         wx.redirectTo({
          url: '/pages/openingvip/openingvip?card_sn='+ this.data.card_sn + '&is_channel=' + this.data.is_channel,
          })
      }else{
        wx.redirectTo({
          url: '/pages/home/index',
        })
      }
    }

    // wx.navigateTo({
    //   url: '/pages/orderSheet/paySuccess',
    // })
    // wx.navigateTo({
    //   url: '/pages/earlyEducation/index',
    // })
  },
  /**
   * 刷新Home接口，设置全局数据
   */
  refreshHome() {

    

    const that = this;

    //从缓存读取home对象
    // let home = wx.getStorageSync('home');
    let home = null;

    if (!home) {
      //取个人中心
      const api = require("../../api/api");
      api.user.home({
        success(resHome) {
      
          let dataHome = resHome.data.data;
        //  console.log("home,resHome1212", resHome)
        //  console.log("dataHome.msg", resHome.data.msg)
          //保存home到本地
          that.setData({
            home: dataHome
          });

          //将home保存到本地缓存
          wx.setStorageSync('home', dataHome);

          //设置全局变量并跳转
          that.setGlobalAndJump();
        }
      });
      return;
    }

    //保存home到本地
    that.setData({
      home: home
    });

    //设置全局变量并跳转
    that.setGlobalAndJump();

  },
  /**
   * 设置全局变量并跳转
   */
  setGlobalAndJump() {
    const that = this;

    let dataHome = this.data.home;

    //是否会员
    //let is_member = dataHome.is_member;
    let is_member = wx.getStorageSync('home').is_member;

    wx.getStorageSync('userInfo')

    //console.log('is_memberis_memberis_member',is_member);

    const util = require("../../utils/util")
    if (!is_member) {
      util.setBeforePlanned(true, is_member)
    } else {
      util.setBeforePlanned(false, is_member)
    }
    // console.log("util.getBeforePlanned()", util.getBeforePlanned())

    //跳转
    that.jumpToPage();
  },

  /**
   * 登录服务器
   */
  loginServer(status = true) {
    let that = this;

    let url = this.data.baseUrl + "/api/user/loginByWechatCode";
    let nickname = wx.getStorageSync('userInfo').nickName;
    let head_image = wx.getStorageSync('userInfo').avatarUrl;

    let nickname1 = this.data.nickName;
    let head_image1 = this.data.avatarUrl;
    let userInfo = wx.getStorageSync('userInfo');

    let data = {
      code: this.data.code,
      channel: this.data.channel,
      hash: this.data.hash,
      nickname,
      head_image
    }
    // console.log("data", data)
    wx.request({
      url: url,
      method: 'POST',
      data: data,
      success(res) {
        // console.log("res", res)
        const util = require("../../utils/util")
        if (status) {
          wx.setStorageSync('token', res.data.data.token)
          wx.setStorageSync('openid', res.data.data.openid)



          util.setLoginData(res.data.data)
          //取个人中心数据，刷新全局变量
          that.refreshHome();
        }
        // console.log("util.getLoginData", util.getLoginData())
      }
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const api = require("../../api/api")
    api.user.getUserChannel({
      success(res) {
        // console.log("getUserChannel.res", res)
      }
    })

    let channel = 'a'
    return {
      title: "联合宝宝",
      path: '/pages/index/index?channel=' + channel,
    }
  },
  clickMe() {
    // wx.login({
    //   success: (res) => {
    //     console.log("login",res)
    //   },
    // })

    this.getUserInfo();
  },
  async getUserInfo() {
    let that = this;
    await wx.getUserProfile({
      desc: '运行联合宝宝',
      success: function (e) {
        // console.log("success,e", e)
        let userInfo = e.userInfo;
        //存到本面变量
        that.setData({
          nickname: userInfo.nickName,
          head_image: userInfo.avatarUrl
        })
        //存到本地缓存
        wx.setStorageSync('userInfo', userInfo)

        //存到全局变量
        const app = getApp();
        app.globalData.userInfo = userInfo;

        setTimeout(function () {
          const api = require("../../api/api")
          api.user.updateUserInfo({
            head_image: userInfo.avatarUrl,
            nickname: userInfo.nickName,
            success(res) {
              //  console.log("getUserChannel.res", res)
            }
          }) // that.loginServer(false);
        }, 1000);


        //console.log("app.globalData", app.globalData)


        //跳转
        // that.jumpToPage();
      }
    })
  }
})